package IOTWeb.com.handler;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.util.Map;

import org.apache.commons.io.IOUtils;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import IOTWeb.com.IOTMain;
import IOTWeb.com.agreementclient.WebServer;
import IOTWeb.com.utils.FileOption;
import IOTWeb.com.utils.Utils;

public class ExcelHandler implements HttpHandler {
	@Override
	public void handle(HttpExchange exchange) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Utils utils = new Utils();
					FileOption fileOption = new FileOption();
					// ��ȡurl
					System.out.println("url:" + exchange.getRequestURI().toString());
					// ��ò�ѯ�ַ���(get)
					String queryString = exchange.getRequestURI().getQuery();
					int num = 0;
					int age = 0;
					Map<String, String> queryStringInfo = utils.formData2Dic(queryString);
					// ��ñ��ύ����(post)
					String postString = IOUtils.toString(exchange.getRequestBody());
					Map<String, String> postInfo = utils.formData2Dic(postString);
					// ��ȡresponseͷ
					Headers responseHeaders = exchange.getResponseHeaders();
					// ��ȡrequestͷ
					Headers requestHeaders = exchange.getRequestHeaders();
					utils.setResponse(responseHeaders);
					OutputStream os = exchange.getResponseBody();
					PrintStream out = new PrintStream(os);
					utils.getIpLocation(exchange);
					if (exchange.getRequestURI().toString().substring(0, 9).equals("/excelsql")) {
						System.out.println("The user asked for resource: " + "excelsql");
						if (!queryStringInfo.get("num").equals("")) {
							num = Integer.valueOf(queryStringInfo.get("num"));
						}
						String title = queryStringInfo.get("title");
						exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK,0);
						int len = utils.excelSQL(out, num, title, exchange);
					}
					else if (exchange.getRequestURI().toString().substring(0, 6).equals("/excel")) {
						System.out.println("The user asked for resource: " + "excel");
						if (!queryStringInfo.get("age").equals("")) {
							age = Integer.valueOf(queryStringInfo.get("age"));
						}
						String name = queryStringInfo.get("name");
						String location = queryStringInfo.get("location");
						String job = queryStringInfo.get("job");
						String title = queryStringInfo.get("title");
						exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK,0);
						int len = utils.addExcel(out, name, age, location, job, title, exchange);
						
					}
					os.close();
					out.close();
				} catch (IOException ie) {
					ie.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
}
